<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-row>
        <el-col :span="5">
          <el-form-item label="患者姓名" prop="patientName" label-width="80px">
            <el-input v-model="queryParams.patientName" placeholder="请输入患者姓名" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="住院号" prop="medicareNo">
            <el-input v-model="queryParams.medicareNo" placeholder="请输入住院号" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="入院日期">
            <el-date-picker v-model="time" style="width:100%" type="daterange" range-separator="至"
              start-placeholder="请选择入院时间" end-placeholder="请选择入院时间" format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd" @change="handletime" clearable>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['workstation:baseInfo:add']">新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="false">
        <el-col :span="12">
          <el-form-item label="出院日期">
            <el-date-picker style="width: 600px !important" v-model="time" type="daterange" range-separator="至"
              start-placeholder="请选择出院时间起始日期" end-placeholder="请选择出院时间结束日期" format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd" @change="handletime" clearable>
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="住院状态" prop="patientState">
            <el-select v-model="queryParams.patientState" placeholder="请输入住院状态" clearable :style="{ width: '100%' }">
              <el-option v-for="(item, index) in patientState" :key="index" :label="item.dictLabel"
                :value="item.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 患者信息展示区 -->
    <div class="mainInfoBox">
      <el-row :gutter="10">
        <el-col :span="4" v-for="item in baseInfoList" :key="item.id">
          <div class="userBox" :class="item.isHaveMonitor == 1 ? 'one' : ''" @click="toUseDetail(item)" >
            <div class="line">
              <span class="title">医院编号:</span><span class="titleNum">yF22RwXQjF8vgXx7</span>
            </div>
            <div class="line">
              <span class="title">患者姓名缩写:</span><span class="titleNum">{{ item.patientName }}</span>
            </div>
            <div class="line">
              <span class="title">住院号:</span><span class="titleNum">{{ item.medicareNo }}</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 患者信息展示区 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :pageSizes="[10, 20, 30,36, 50]"
      @pagination="getList" />

    <!-- 添加或修改患者基本信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" label-position="left">
        <el-form-item label="患者主索引" prop="patientNo">
          <el-input v-model="form.patientNo" placeholder="请输入患者主索引" />
        </el-form-item>
        <el-form-item label="住院号" prop="medicareNo">
          <el-input v-model="form.medicareNo" placeholder="请输入住院号" />
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="patientSex">
          <el-select
              v-model="form.patientSex"
              placeholder="请选择"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in userSex"
                :key="index"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="patientAge" :error="errormsg1">
          <el-input  @input="input1" v-model="form.patientAge" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="民族" prop="nation">
          <el-input v-model="form.nation" placeholder="请输入民族" />
        </el-form-item>
        <el-form-item label="身高" prop="patientHeight">
          <el-input  v-model.number="form.patientHeight" type="number" min="0" placeholder="请输入身高" />
        </el-form-item>
        <el-form-item label="体重" prop="patientWeight">
          <el-input  v-model.number="form.patientWeight" type="number" min="0" placeholder="请输入体重" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phoneNo">
          <el-input v-model="form.phoneNo" placeholder="请输入联系方式" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <router-view> </router-view>
  </div>
</template>

<script>
import {
  listBaseInfo,
  getBaseInfo,
  delBaseInfo,
  addBaseInfo,
  updateBaseInfo,
} from "@/api/workstation/baseInfo";
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect,
  deptList,
} from "@/api/system/user";
import { getDicts } from "@/api/system/dict/data";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "BaseInfo",
  components: { Treeselect },
  data() {
    return {
      setDisabled: {
        // 返回禁用时间
        disabledDate(time) {
          return time.getTime() > Date.now(); // 可选历史天、可选当前天、不可选未来天
          // return time.getTime() > Date.now() - 8.64e7;  // 可选历史天、不可选当前天、不可选未来天
          // return time.getTime() < Date.now() - 8.64e7;  // 不可选历史天、可选当前天、可选未来天
          // return time.getTime() < Date.now(); // 不可选历史天、不可选当前天、可选未来天
        },
      },
      // 部门树选项
      deptOptions: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者基本信息表格数据
      baseInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 36,
        doctorName: undefined, // 住院医师的名字  搜索
        medicareNo: undefined,
        patientName: undefined,
        // medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        // admissionDate: undefined,
        admissionTime: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        params: {},
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: "患者ID不能为空", trigger: "blur" }],
        patientName: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" },
        ],
        medicalRecordNo: [
          { required: true, message: "医院编号不能为空", trigger: "blur" },
        ],
        patientNo: [
          { required: true, message: "ID号不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "科室/病区不能为空", trigger: "blur" },
        ],
        admissionTime: [
          { required: true, message: "入院时间不能为空", trigger: "blur" },
        ],
        doctorId: [
          { required: true, message: "临床药师不能为空", trigger: "blur" },
        ],
        bedNo: [{ required: true, message: "床号不能为空", trigger: "blur" }],
        firstDiagnose: [
          { required: true, message: "第一诊断不能为空", trigger: "blur" },
        ],
        guardianLevel: [
          { required: true, message: "监护分级不能为空", trigger: "blur" },
        ],
        patientState: [
          { required: true, message: "住院状态不能为空", trigger: "blur" },
        ],
        medicareNo: [
          { required: true, message: "住院号不能为空", trigger: "blur" },
        ],
        payWay: [
          { required: true, message: "付费方式不能为空", trigger: "blur" },
        ],
        sourceInfo: [
          { required: true, message: "数据来源不能为空", trigger: "blur" },
        ],
      },
      guardianLevel: [], // 监护分级
      patientState: [], // 住院状态
      userSex: [], // 患者性别
      payWay: [], // 付费方式
      sourceInfo: [], // 患者信息来源
      DoctorList: [], // 对应科室的医生列表
      msg: {}, // 患者管理页搜索条件
      time: "", // 起始日期
      errormsg1: "", // 起始日期
    };
  },
  computed: {
    role() {
      return this.$store.state.user.roles;
    },
    useInfo() {
      return this.$store.state.user.user;
    },
  },
  created() {
    this.getList();
    // 字典查询  监护分级
    getDicts("guardian_level").then((res) => {
      this.guardianLevel = res.data;
    });
    // 字典查询  住院状态
    getDicts("patient_state").then((res) => {
      this.patientState = res.data;
    });
    // 字典查询  患者性别
    getDicts("sys_user_sex").then((res) => {
      this.userSex = res.data;
    });
    // 字典查询  付费方式
    getDicts("pay_way").then((res) => {
      this.payWay = res.data;
    });
    // 字典查询  患者信息来源
    getDicts("source_info").then((res) => {
      this.sourceInfo = res.data;
    });
  },
  methods: {
    input1(val) {
      if (!val) {
        this.errormsg1 = ""
        return;
      }
      const value = val.trim(); // 获取输入框的值，并去除空格
      let reg = /^(0|[1-9]\d?|1[01]\d|120)$/;
      if (!reg.test(value)) {
        // 如果输入的值不符合要求，则清空输入框
        this.errormsg1 = "请输入0-120的整数";
        this.form.patientAge = "";
      } else {
        this.errormsg1 = "";
      }
    },
    handletime(val) {
      console.log(val);
      if (val) {
        this.queryParams.params = {};
        this.queryParams.params["beginDate2"] = val[0];
        this.queryParams.params["endDate2"] = val[1];
        console.log(this.queryParams);
      } else {
        this.queryParams.params = {};
      }
    },
    // 去患者详情页
    toUseDetail(item) {
      if(item.isHaveMonitor == 1) return this.$modal.msgError('该患者已经被其他老师建过表，请选择未建表的患者！')
      this.$router.push({
        path: "/electronicDetectionForm",
        query: {
          medicalRecordNo: item.medicalRecordNo,
        },
      });
    },
    /** 查询科室下拉树结构 */
    getDeptTree() {
      console.log(this.role, this.useInfo);
      // 质控员 拥有所有科室
      if (this.role.includes("quality")) {
        deptTreeSelect().then((response) => {
          this.deptOptions = response.data;
        });
        return;
      }
      console.log("用户信息", this.useInfo);
      // 指定了常驻病区 下拉查询
      if (this.useInfo.longDept) {
        let params = {};
        params.params = {};
        params.params["longDept"] = this.useInfo.longDept;
        deptList(params).then((response) => {
          // this.deptOptions = response.data;
          let arr = [];
          response?.data.forEach((item) => {
            let obj = {
              id: item.deptId,
              label: item.deptName,
              parentId: item.parentId,
            };
            arr.push(obj);
          });
          this.deptOptions = arr;
        });
      } else {
        // 指定了科室  没有指定病区
        let params = {
          parentId: this.useInfo.deptId,
        };
        deptList(params).then((response) => {
          // this.deptOptions = response.data;
          let arr = [];
          response?.data.forEach((item) => {
            let obj = {
              id: item.deptId,
              label: item.deptName,
              parentId: item.parentId,
            };
            arr.push(obj);
          });
          this.deptOptions = arr;
        });
      }
    },
    /** 查询患者基本信息列表 */
    getList() {
      this.loading = true;
      listBaseInfo(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.baseInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        patientName: undefined,
        medicalRecordNo: undefined,
        patientNo: undefined,
        deptId: undefined,
        admissionDate: undefined,
        doctorId: undefined,
        bedNo: undefined,
        firstDiagnose: undefined,
        guardianLevel: undefined,
        patientState: undefined,
        patientSex: undefined,
        patientAge: undefined,
        patientProfession: undefined,
        nation: undefined,
        patientHeight: undefined,
        patientWeight: undefined,
        patientBmi: undefined,
        phoneNo: undefined,
        payWay: undefined,
        sourceInfo: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.time = "";
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加患者基本信息";
    },
    handleDoctorName(val) {
      let person = this.DoctorList.filter((item) => {
        return item.userId == val;
      });
      this.form.doctorName = person[0].nickName;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getBaseInfo(id).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改患者基本信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateBaseInfo(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            this.form.sourceInfo = "0"; // 代表是手工录入
            addBaseInfo(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除患者基本信息编号为"' + ids + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delBaseInfo(ids);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "workstation/baseInfo/export",
        {
          ...this.queryParams,
        },
        `baseInfo_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-form-item__label-wrap {
  margin-left: 0 !important;
}
// 一级护理
.one {
  background-color: #f9d9dd !important;
}

// 二级护理
.two {
  background-color: #fef0df !important;
}

// 出院患者
.useLeaveStatus {
  display: inline-block;
  text-align: center;
  line-height: 36px;
  width: 73px;
  height: 36px;
  background-color: rgba(245, 154, 35, 1);
  font-size: 14px;
  color: #ffffff;
}

.mainInfoBox {

  // display: grid;
  // /* 声明列的宽度,数字3表示的重复3次，即有3列宽度为200px*/
  // grid-template-columns: repeat(5, 360px);
  // /* 声明行间距和列间距 */
  // grid-gap: 20px;
  // /* 分别表示两行的高度 */
  // grid-template-rows: 320px;
  .userBox {
    margin-top: 10px;
    padding: 10px 10px 10px 20px;
    //width: 315px;
    //height: 355px;
    box-sizing: border-box;
    background-color: #e9f4d8;
    cursor: pointer;

    .line {
      margin-top: 10px;
      display: flex;
      align-items: center;

      // 住院患者
      .useStatus {
        display: inline-block;
        text-align: center;
        line-height: 36px;
        width: 73px;
        height: 36px;
        background-color: rgba(112, 182, 3, 1);
        font-size: 14px;
        color: #ffffff;
      }

      .title {
        display: inline-block;
        width: 90px !important;
        font-family: "PingFang SC ", "PingFang SC", sans-serif;
        font-weight: 400;
        font-style: normal;
        font-size: 14px;
        color: #86909c;
      }

      .titleNum {
        // display: inline-block;
        // width: 220px !important;
        margin-left: 5px;
        font-family: "PingFang SC ", "PingFang SC", sans-serif;
        font-weight: 400;
        font-style: normal;
        font-size: 14px;
        color: #1d2129;
      }
    }
  }
}
</style>
